package com.zry.study.ui.base

import android.annotation.TargetApi
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.Html
import kr.co.namee.permissiongen.PermissionGen


/**
 * Created by zry on 2018/2/7.
 */
abstract class PermissionActivity : BaseActivity() {
	
	private var builder: AlertDialog.Builder? = null
	private var alertDialog: AlertDialog? = null
	private fun onPermissionSuccess() {
	
	}
	
	private fun onPermissionFail() {
		showMissPermissionDialog()
	}
	
	private fun getPermission(vararg permissions: String) {
		if (Build.VERSION.SDK_INT >= 23) {
			if (findDeniedPermissions(this, *permissions).isNotEmpty()) {
				PermissionGen.with(this).addRequestCode(100).permissions(*permissions).request()
			} else {
				onPermissionSuccess()
			}
		} else {
			onPermissionSuccess()
		}
	}
	
	@TargetApi(value = Build.VERSION_CODES.M)
	private fun findDeniedPermissions(activity: Activity, vararg permission: String): List<String> {
		val denyPermissions: ArrayList<String> = arrayListOf()
		permission.filterTo(denyPermissions) { activity.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
		return denyPermissions
	}
	
	//申请拍照和文件读写权限
	fun getTakePicPermission() {
		getPermission(android.Manifest.permission.CAMERA, //相机
			android.Manifest.permission.READ_EXTERNAL_STORAGE, //SD卡读取权限
			android.Manifest.permission.WRITE_EXTERNAL_STORAGE, //SD卡写入权限
			
			//                android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS,//创建SD卡文件读写和删除的权限
			//                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,//操作SD卡的权限
			
			android.Manifest.permission.ACCESS_COARSE_LOCATION, //定位
			android.Manifest.permission.ACCESS_FINE_LOCATION, //定位权限
			android.Manifest.permission.RECORD_AUDIO, //允许程序录制音频
			android.Manifest.permission.READ_PHONE_STATE, //读取手机当前状态
			android.Manifest.permission.ACCESS_WIFI_STATE, android.Manifest.permission.ACCESS_NETWORK_STATE, android.Manifest.permission.MODIFY_AUDIO_SETTINGS, android.Manifest.permission.WRITE_SETTINGS)
	}
	
	override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
		for (i in grantResults.indices) {
			if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
				onPermissionFail()
				return
			}
		}
		onPermissionSuccess()
	}
	
	
	/**
	 * 丢失权限，进行弹框设置
	 */
	private fun showMissPermissionDialog() {
		if (builder == null) {
			builder = AlertDialog.Builder(this)
			builder?.setTitle("帮助")
			val msg = "当前应用缺少必要权限。<br>\r请点击\"设置\"-\"权限\"-打开所需权限。<br>\r\r最后点击两次后退按钮，即可返回。"
			builder?.setMessage(Html.fromHtml(msg))
			//materialDialog.setMovementMethod(LinkMovementMethod.getInstance());
			builder?.setPositiveButton("退出", { dialog, which -> alertDialog?.dismiss() })
			builder?.setNegativeButton("设置", { dialog, which ->
				alertDialog?.dismiss()
				startAppSettings()
			})
			alertDialog = builder?.create()
			alertDialog?.show()
		} else {
			alertDialog?.show()
		}
	}
	
	// 启动应用的设置
	private fun startAppSettings() {
		try {
			val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
			intent.data = Uri.parse("package:" + packageName)
			startActivity(intent)
		} catch (e: Exception) {
			e.printStackTrace()
		}
		
	}
}